<?php
/**
 * класс для работы с таблицей "Победители тендеров"
 *
 * @author kingop
 */
class DatabaseObject_TendersWinners extends DatabaseObject {
    
    public $tender = null;
    public $request = null;
    
    public function __construct($db) {
        parent::__construct($db, 'tenders_winners', 'id');
        
        $this->add('idTender');
        $this->add('idRequest');
    }
    
    protected function postLoad() {
        parent::postLoad();
        
        $this->request = new DatabaseObject_Requests($this->getDb());
        $this->request->load($this->idRequest);
        $this->tender = $this->request->tender;
        
        return true;
    }
    
    public static function FinishTender($db, $idRequest) {
       
        
        $request = new DatabaseObject_Requests($db);
        $request->load($idRequest);
        
        $tWinner = new DatabaseObject_TendersWinners($db);
        if (!$tWinner->load($request->tender->getId(), 'idTender'))
        {
            $tWinner->where('idRequest = '.$idRequest);
        }
        else
        {
        $tWinner->idTender = $request->tender->getId();
        $tWinner->idRequest = $idRequest;
        }
        $tWinner->save();
        
        // отправим тендер в архив
        $request->tender->archive = 1;
        $request->tender->save();
    }
    
    public static function GetWinner($db, $idTender = 0, $idRequest = 0)
    {
        $select = self::_GetBaseQuery($db, array());
        $select->from(null, '*');
        if ($idTender)
        $select->where('idTender = ?', $idTender);

        if ($idRequest)
        $select->where('idRequest = ?', $idRequest);
         
        $data = $db->fetchAll($select);

        $winner = self::BuildMultiple($db, __CLASS__, $data);
        
        return $winner; 
    }
     private static function _GetBaseQuery($db, $options) {
        // инициализация настроек
        $defaults = array();

        foreach ($defaults as $k => $v) {
            $options[$k] = array_key_exists($k, $options) ? $options[$k] : $v;
        }

        // создание запроса на получение
        $select = $db->select();
        $select->from(array('p' => 'tenders_winners'), array());

        return $select;
    }
}

?>
